package com.foo.LoadingData;

import java.io.FileOutputStream;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.ejb.Stateless;
import javax.jms.*;
import javax.jms.Queue;
import javax.naming.Context;
import javax.naming.InitialContext;

import com.foo.CompressData.Compress;
import com.foo.Entity.HistoricalData;
import com.foo.FileParser.FileParser;
import com.foo.DataSender.*;

/**
 * Session Bean implementation class DataLoader
 */
@Stateless
public class DataLoader implements DataLoaderRemote, DataLoaderLocal {

	private Compress objCompress;
	private FileParser objFileParser;
	private DataSender objDataSender;
	Queue queue = null;
	QueueConnectionFactory factory = null;
	QueueConnection connection = null;
	QueueSender sender = null;
	QueueSession session = null;
	
    /**
     * Default constructor. 
     */
    public DataLoader() {
        
    }

	@Override
	public String storeData(byte[] fileData, int startPos, int endPos) {
		FileOutputStream fileOut;
		try
		{
			//Step 1: Storing the file to the remote location
			java.util.Date date = new java.util.Date() ; 
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ; 
			//String fileName = StringConstant.fileSavePath + dateFormat.format(date) +".txt";
			String fileName = dateFormat.format(date) +".txt";
			fileOut = new FileOutputStream(fileName);                
			fileOut.write(fileData, startPos, (endPos - startPos));                
			fileOut.flush();                
			fileOut.close();
			
			//Step 2: Pass the file to the Archival Component
			objCompress = new Compress();
			String compressedFileName = objCompress.storeFile(fileName);
			if(compressedFileName != null)
			{
				System.out.println("Compression successfull!!!!");
			}
			
			//Step 3: Pass the file to File parser to read only 3 months data
			String[] startendTag = compressedFileName.split("-");
			String starttag ="";
			if(startendTag.length >0)
			{
				if(startendTag[0]!= null)
				{
					starttag = startendTag[0];
				}
							
			SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMdd");
			java.util.Date startDate = (java.util.Date) dateFormater.parse(starttag);
						
			Calendar cal = Calendar.getInstance();
			cal.setTime(startDate);
			int month = cal.get(Calendar.MONTH);
			int threeMonths = month + 3;
			cal.set(Calendar.MONTH,threeMonths);
			java.util.Date threeMonthDate = cal.getTime();
			
			objFileParser = new FileParser();
			String data = objFileParser.readData(compressedFileName, startDate, threeMonthDate);
			String[] stockDataArray = data.split(":");			
			//Storing the data into Historical Entity Object
			HistoricalData[] newstock = new HistoricalData[stockDataArray.length];
			for(int i=0; i<stockDataArray.length; i++)
    		{
    	    	String[] stockData = stockDataArray[i].split(",");
    	    	if(stockData != null && stockData.length >0)
    	    	{
	    	    	//SimpleDateFormat dateFormater1 = new SimpleDateFormat("yyyyMMdd");
	    	    	java.util.Date parsedDate = (java.util.Date) dateFormater.parse(stockData[0]);
	    	    	java.sql.Date deals_date = new java.sql.Date(parsedDate.getTime());
	    			
	    			String ticker_symbol = stockData[1];
	    			
	    			double open_value = Double.parseDouble(stockData[2]);
	    			double high_value = Double.parseDouble(stockData[3]);
	    			double low_value = Double.parseDouble(stockData[4]);
	    			double close_value = Double.parseDouble(stockData[5]);
	    			long volume = Long.parseLong(stockData[6]);
	    			HistoricalData sData = new HistoricalData();
	    			sData.setOpen_value(open_value);
	    			sData.setClose_value(close_value);
	    			sData.setHigh_value(high_value);
	    			sData.setLow_value(low_value);
	    			sData.setVolume(volume);
	    			sData.setDeals_date(deals_date);
	    			sData.setTicker_symbol(ticker_symbol);
	    			
	    			newstock[i]= sData;
    	    	}
    		}
			//Step 4: Pass the data as Object List to Queue
			sendObjectMessage(newstock);
			System.out.println("Data Sent to queue!!!!");
			return data;
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			return null;
		}		
	}
	public void sendObjectMessage(HistoricalData[] data)
	{
		try
		{
			Queue queue = null;
			QueueConnectionFactory qfactory = null;
			QueueConnection qconnection = null;
			QueueSender qsender = null;
			QueueSession qsession = null;
			
			//Load Historical Data
			Properties props = new Properties();
			props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
			props.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
			props.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
			Context ctx = new InitialContext(props);
			qfactory = (QueueConnectionFactory) ctx.lookup("XAConnectionFactory");
			qconnection = qfactory.createQueueConnection();
			qsession = qconnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
			queue = (Queue) ctx.lookup("queue/HistoricalDataStorage");
			qsender = qsession.createSender(queue);
			//create and set a message to send
			ObjectMessage message = qsession.createObjectMessage();
			message.setObject(data);
			
			qsender.send(message);
			qsession.close ();
			qconnection.close();
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
		}

	}
}
